package com.riekoff.particlecubeworld.editor;

import java.util.ArrayList;
import java.util.List;

import cc.creativecomputing.graphics.CCColor;
import cc.creativecomputing.graphics.texture.CCTexture.CCTextureFilter;
import cc.creativecomputing.graphics.texture.CCTexture.CCTextureTarget;
import cc.creativecomputing.graphics.texture.CCTexture2D;
import cc.creativecomputing.graphics.texture.CCTextureData;
import cc.creativecomputing.math.CCMath;

public class AColorMap {
	
	private class AColorWithPropability{
		private CCColor _myColor;
		
		private float _myPropability;
		
		public AColorWithPropability(CCColor theColor, float thePropability){
			_myColor = theColor;
			_myPropability = thePropability;
		}
	}
	
	protected int _myNumberOfZones;
	
	private boolean _myHasChanged = true;
	
	protected ArrayList<AColorWithPropability>[] _myColors;
	
	protected String[] _myFiles;
	
	private CCTexture2D _myTexture = null;
	
	public AColorMap(int theNumberOfZones){
		_myNumberOfZones = theNumberOfZones;
		_myColors = new ArrayList[_myNumberOfZones];
		_myFiles = new String[_myNumberOfZones];
	}
	
	public void clear(){
		for(int i = 0; i < _myNumberOfZones;i++){
			_myColors[i] = new ArrayList<>();
		}
	}

	public void addColor(int theZone, CCColor theColor, float thePropability){
		_myColors[theZone].add(new AColorWithPropability(theColor, thePropability));
		_myHasChanged = true;
	}
	
	public void randomize(int maxNumColorsPerZone){
		for(int i = 0; i < _myNumberOfZones;i++){
			_myColors[i] = new ArrayList<>();
			int myNumberOfColors = (int)CCMath.random(maxNumColorsPerZone) + 1;
			for(int j = 0; j < myNumberOfColors;j++){
				addColor(i, CCColor.random(),CCMath.random());
			}
		}
	}
	
	public CCTextureData createData(boolean invert){
		CCTextureData myData = new CCTextureData(100, _myNumberOfZones);
		for(int zone = 0; zone < _myNumberOfZones; zone++){
			float myProb = 0;
			for(AColorWithPropability myColor:_myColors[zone]){
				myProb += myColor._myPropability;
			}
			int myX = 0;
			CCColor myLastColor = _myColors[zone].get(0)._myColor;
			for(AColorWithPropability myColor:_myColors[zone]){
				int myRange = (int)(myColor._myPropability / myProb * 100);
				for(int i = 0; i < myRange;i++){
					myLastColor = myColor._myColor;
					myData.setPixel(myX + i, invert ? _myNumberOfZones - 1 - zone : zone, myColor._myColor);
				}
				myX += myRange;
			}
			for(;myX < 100;myX++){
				myData.setPixel(myX, invert ? _myNumberOfZones - 1 - zone : zone, myLastColor);
			}
		}
		return myData;
	}
	
	public CCTexture2D texture(){
		if(_myHasChanged){
			CCTextureData myData = createData(false);
			_myTexture = new CCTexture2D(myData, CCTextureTarget.TEXTURE_RECT);
			_myTexture.textureFilter(CCTextureFilter.NEAREST);
		}
		_myHasChanged = false;
		return _myTexture;
	}
}
